package com.tiantianyuegou.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.TimeUtils;
import com.tiantianyuegou.util.Tools;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.tiantianyuegou.R;
import com.tiantianyuegou.app.SysApplication;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.Ad;
import com.tiantianyuegou.model.RobRedbagInfoModel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 抢红包
 * Created by huyang on 2016/2/17 0017.
 */
public class RobRedBagActivity extends BaseActivity {

    private ImageView iv_rob;//抢红包
    private ImageView iv_cancel;
    private ImageView iv_share;
    private TextView tv_count;
    private TextView tv_auto;//跑马灯
    private ViewPager adv_redbag;//抢红包界面轮播图
    private PopupWindow successPopupWindow, failePopUpWindow, sharePopupWindow;
    private String TAG = "RobRedBagActivity";
    private String trId;
    private LoadingDialog loadingDialog;
    private Button btn_qq, btn_weixin, btn_circle, btn_sina;//分享
    private UMImage image;
    private TextView cancel;//取消分享
    private List<Ad> adlist;
    private LinearLayout linearDot;
    private ImageView ADtips[];
    private int ADCurrentPage = 0;//当前页码
    private List<String> mTrId;//红包id集合
    private View view;
    private WindowManager window;
    private List<RobRedbagInfoModel> data;
    private boolean isSuccess = true;
    //private String money;

    private static ByteArrayOutputStream baos = null;
    private static Bitmap bitmap = null;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            adv_redbag.setCurrentItem(adv_redbag.getCurrentItem() + 1);
            handler.sendEmptyMessageDelayed(0, 3000);
        }
    };

    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mHandler.postDelayed(this, 1000 * 1800);
            getWinerInfo();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_robredbag);
        Tools.changeSystemBar(this);
        setTitle("抢红包");
        initViews();
        loadAdv();
        getWinerInfo();
        //openRedBag(trId);
        SysApplication.getInstance().shareInit();//分享相关设置初始化

        mHandler.postDelayed(runnable, 1000 * 1800);

    }

    @Override
    public void findViewByIds() {
        iv_rob = (ImageView) findViewById(R.id.iv_rob);
        tv_count = (TextView) findViewById(R.id.tv_redbagcount);
        adv_redbag = (ViewPager) findViewById(R.id.adv_redbag);
        linearDot = (LinearLayout) findViewById(R.id.dot);
        tv_auto = (TextView) findViewById(R.id.tv_show);

        data = new ArrayList<>();


        //Log.e(TAG,Html.fromHtml(result.toString())+"");
    }

    @Override
    public void initListener() {

        loadingDialog = new LoadingDialog(this);
        adlist = new ArrayList<Ad>();
        mTrId = new ArrayList<>();
        iv_rob.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                robRedBag(trId);

            }
        });
    }

    @Override
    public void initData() {

        loadingDialog.setMsg("正在加载");
        loadingDialog.showDialog();

        RequestParams params = new RequestParams();
        params.addBodyParameter("", "");

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.REDBAG_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "rob    redbag: " + response.result);

                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取红包列表失败");
                } else {
                    try {
                        JSONObject jsonObjec = new JSONObject(response.result);
                        String code = jsonObjec.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray list = jsonObjec.getJSONArray("list");
                            if (list.length() > 0) {
                                mTrId.clear();
                                for (int i = 0; i < list.length(); i++) {
                                    JSONObject temp = list.getJSONObject(i);
                                    String trId = temp.getString("trId");
                                    String trTotalAmount = temp.getString("trTotalAmount");
                                    String trTotalCount = temp.getString("trTotalCount");
                                    String trStart = temp.getString("trStart");
                                    String trEnd = temp.getString("trEnd");

                                    mTrId.add(trId);
                                    Log.e(TAG, "-------size=" + mTrId.size());
                                    tv_count.setText("“ " + trTotalCount + " ”");
                                }

                                //每次存入红包id时打乱顺序，并取出集合中index为0红包id
                                Collections.shuffle(mTrId);
                                trId = mTrId.get(0);
                            }
                        } else if (code.equalsIgnoreCase("102")) {
                            showMsg("数据异常");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查您的网络");
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    //抢红包
    public void robRedBag(String trId) {

        loadingDialog.setMsg("正在加载");
        loadingDialog.showDialog();

        RequestParams params = new RequestParams();
        params.addBodyParameter("trId", trId);
        params.addBodyParameter("tmId", SPHelper.getTmId());
        System.out.println("----------trid=" + trId);

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.ROB_REDBAG, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                loadingDialog.dismiss();

                Log.e(TAG, "rob    redbag:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("获取红包信息失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            showSuccessPopWindows();
                            showSuccess();
                        } else if (code.equalsIgnoreCase("104")) {
                            showMsg("本次抢红包活动已经结束");
                        } else if (code.equalsIgnoreCase("105")) {
                            String message = jsonObject.getString("message");
                            showMsg(message);
                        } else if (code.equalsIgnoreCase("107")) {
                            showMsg("您没有红包，不能参与抢红包活动");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查您的网络");
            }
        });
    }

    public void getWinerInfo() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("", "");

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.REDBAG_AUTOSCROLL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e(TAG, "  get winer info  " + responseInfo.result);

                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("获取中奖信息失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray info = jsonObject.getJSONArray("info");
                            for (int i = 0; i < info.length(); i++) {
                                JSONObject temp = info.getJSONObject(i);
                                String tmAccount = temp.getString("tmAccount");
                                String trd_amount = temp.getString("trd_amount");
                                String trd_lottery_time = temp.getString("trd_lottery_time");

                                RobRedbagInfoModel model = new RobRedbagInfoModel();
                                model.setTmAccount(tmAccount);
                                model.setTrd_amount(trd_amount);
                                model.setTrd_lottery_time(TimeUtils.convertTimeYMD(Long.valueOf(trd_lottery_time)));
                                data.add(model);
                            }
                            StringBuffer result = new StringBuffer();
                            for (int i = 0; i < data.size(); i++) {
                                result.append("<font color=\"#ff0000\">").append(data.get(i).getTmAccount().substring(0, 3)).append("****").append(data.get(i).getTmAccount().substring(7, 11)).append("</font><br>");
                                result.append("<font color=\"#ffffff\">获得</font><br>");
                                result.append("<font color=\"#ff0000\">").append(data.get(i).getTrd_amount()).append("</font><br>");
                                result.append("<font color=\"#ffffff\">元红包</font><br>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp");
                                result.append("<font color=\"#ffffff\">").append(data.get(i).getTrd_lottery_time()).append("</font><br>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp");
                            }
                            tv_auto.setText(Html.fromHtml(result.toString()));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("解析异常");
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }

    //拆红包
    public void openRedBag(String trId) {

        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");
        RequestParams params = new RequestParams();

        params.addBodyParameter("trId", trId);
        params.addBodyParameter("tmId", SPHelper.getTmId());
        System.out.println("----------trid=" + trId);

        loadData(HttpRequest.HttpMethod.POST, ApiDefine.OPEN_REDBAG, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                loadingDialog.dismiss();
                Log.e(TAG, "open    redBag:" + responseInfo.result);
                if (TextUtils.isEmpty(responseInfo.result)) {
                    showMsg("");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(responseInfo.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            String money = jsonObject.getString("money");
                           /* Intent intent = new Intent(RobRedBagActivity.this, OpenRedBagActivity.class);
                            intent.putExtra("money", money);
                            Log.e(TAG, "-----money=" + money);
                            startActivity(intent);*/

                        } else {

                            isSuccess=false;
                            showFailePopWindows();
                            showFaile();
                            successPopupWindow.dismiss();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查您的网络设置");
            }
        });

    }

    //抢到红包,显示弹窗
    public void showSuccessPopWindows() {
        //引入窗口布局文件
        view = getLayoutInflater().inflate(R.layout.popwindow_robredbag_success, null);
        //创建popupwindow对象
        successPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT, true);
        successPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        //设置点击窗口外边窗口消失
        successPopupWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        successPopupWindow.setFocusable(true);
        //getWindow().setBackgroundDrawableResource(R.drawable.share_redbag_bg);

        iv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);
        iv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                successPopupWindow.dismiss();
            }
        });
        iv_share = (ImageView) view.findViewById(R.id.iv_share);
        iv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSharePopWindows();
                shareShow();
            }
        });
    }

    //未抢到红包,显示弹窗
    public void showFailePopWindows() {
        //引入窗口布局文件
        view = getLayoutInflater().inflate(R.layout.popwindow_robredbag_faile, null);
        //创建popupwindow对象
        failePopUpWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT, false);
        failePopUpWindow.setBackgroundDrawable(new BitmapDrawable());
        //设置点击窗口外边窗口消失
        failePopUpWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        failePopUpWindow.setFocusable(true);
        //getWindow().setBackgroundDrawableResource(R.drawable.share_redbag_bg);

        iv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);
        iv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                failePopUpWindow.dismiss();
            }
        });
        iv_share = (ImageView) view.findViewById(R.id.iv_share);
        iv_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSharePopWindows();
                shareShow();
//                if (failePopUpWindow.isShowing()) {
//                    failePopUpWindow.dismiss();
//                }
            }
        });

    }

    //红包分享,显示弹窗
    public void showSharePopWindows() {
        //引入窗口布局文件
        view = getLayoutInflater().inflate(R.layout.popwindow_share, null);
        //创建popupwindow对象
        sharePopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.FILL_PARENT, false);
        sharePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        //设置点击窗口外边窗口消失
        sharePopupWindow.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        sharePopupWindow.setFocusable(true);
        //getWindow().setBackgroundDrawableResource(R.drawable.share_redbag_bg);

        btn_circle = (Button) view.findViewById(R.id.btn_circle);
        btn_weixin = (Button) view.findViewById(R.id.btn_weixin);
        btn_qq = (Button) view.findViewById(R.id.btn_qq);
        btn_sina = (Button) view.findViewById(R.id.btn_sina);
        cancel = (TextView) view.findViewById(R.id.tv_cancel_share);

        image = new UMImage(RobRedBagActivity.this, R.mipmap.q_10_1);


        btn_circle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                successPopupWindow.dismiss();
                sharePopupWindow.dismiss();
                new ShareAction(RobRedBagActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                        .withText("hongbao")
                        .withMedia(image)
                        .withTargetUrl("http://www.baidu.com")
                        .share();
            }
        });
        btn_qq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                successPopupWindow.dismiss();
                sharePopupWindow.dismiss();
                new ShareAction(RobRedBagActivity.this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                        .withText("hongbao")
                        .withMedia(image)
                        .withTargetUrl("http://www.baidu.com")
                        .share();
            }
        });
        btn_sina.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                successPopupWindow.dismiss();
                sharePopupWindow.dismiss();
                new ShareAction(RobRedBagActivity.this).setPlatform(SHARE_MEDIA.SINA).setCallback(umShareListener)
                        .withText("hongbao")
                        .withMedia(image)
                        .withTargetUrl("http://www.baidu.com")
                        .share();
            }
        });
        btn_weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                successPopupWindow.dismiss();
                sharePopupWindow.dismiss();
                new ShareAction(RobRedBagActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                        .withText("hongbao")
                        .withMedia(image)
                        .withTargetUrl("http://www.baidu.com")
                        .share();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sharePopupWindow.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (isSuccess) {
                openRedBag(trId);
            }else{
                //failePopUpWindow.dismiss();
                isSuccess=true;
            }
            //failePopUpWindow.dismiss();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(RobRedBagActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(RobRedBagActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };

    private void showSuccess() {
        successPopupWindow.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0);
    }

    private void showFaile() {
        failePopUpWindow.showAtLocation(this.findViewById(R.id.main), Gravity.CENTER, 0, 0);
    }

    private void shareShow() {
        sharePopupWindow.showAtLocation(this.findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, -50);
    }

    //加载轮播图
    public void loadAdv() {
        RequestParams params = new RequestParams();
        params.addBodyParameter("tacCataId", "3");
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.HOME_ADV_LIST, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("加载轮播图失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONArray result = jsonObject.getJSONArray("result");
                            if (result.length() > 0) {
                                for (int i = 0; i < result.length(); i++) {
                                    JSONObject temp = result.getJSONObject(i);
                                    String tacId = temp.getString("tacId");
                                    String tacPhoneImage = temp.getString("tacPhoneImage");
                                    String tacLink = temp.getString("tacLink");

                                    Ad adImage = new Ad(tacId, tacPhoneImage, tacLink);
                                    adlist.add(adImage);

                                }
                                changeAdv();
                                Log.e(TAG, adlist.size() + "sadsadasd");
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }

    public void changeAdv() {
        ADtips = new ImageView[adlist.size()];
        for (int i = 0; i < ADtips.length; i++) {
            ImageView img = new ImageView(this);
            LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(20, 20);
            ADtips[i] = img;
            if (i != 0) {
                layoutParam.leftMargin = 5;
                img.setBackgroundResource(R.mipmap.homead_nochoose);//黑色背景
            } else {
                img.setBackgroundResource(R.mipmap.homead_choose);// 蓝色背景
            }
            linearDot.addView(img, layoutParam);
        }
        // 通过适配器引入图片
        MyViewPager mAdapter = new MyViewPager(this, adlist);
        adv_redbag.setAdapter(mAdapter);
        adv_redbag.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                ADtips[ADCurrentPage]
                        .setBackgroundResource(R.mipmap.homead_nochoose);
                ADCurrentPage = position;
                ADtips[position]
                        .setBackgroundResource(R.mipmap.homead_choose);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        // 计时器
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_nochoose);
                        if (ADCurrentPage == ADtips.length - 1) {
                            ADCurrentPage = 0;
                        } else {
                            ADCurrentPage++;
                        }
                        ADtips[ADCurrentPage]
                                .setBackgroundResource(R.mipmap.homead_choose);
                        adv_redbag
                                .setCurrentItem(ADCurrentPage);
                    }
                });
            }
        }, 5000, 5000);
        // 轮播图结束
    }


    class MyViewPager extends PagerAdapter {
        private Context context;
        private List<Ad> data = new ArrayList<>();

        public MyViewPager(Context context, List<Ad> data) {
            this.context = context;
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        /**
         * true表示无需创建 false表示需要创建
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        /**
         * 设置view多个界面
         */
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            Ad adImage = adlist.get(position % adlist.size());
            View view = View.inflate(RobRedBagActivity.this, R.layout.adapter, null);
            ImageView image = (ImageView) view.findViewById(R.id.image);
//            ImageLoader.getInstance().init(
//                    ImageLoaderConfiguration.createDefault(activity));
            ImageLoader.getInstance().displayImage(adImage.getTacPhoneImage(), image);
            image.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(RobRedBagActivity.this, WebActivity.class);
                    intent.putExtra("type", "CategoryAdv");
                    intent.putExtra("url", adlist.get(position % adlist.size()).getTacLink());
                    startActivity(intent);
                }
            });
            container.addView(view);
            return view;
        }

        /**
         * 销毁page position:当前要销毁第几个page object：当前需要销毁的page
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // super.destroyItem(container, position, object);
            container.removeView((View) object);
        }
    }
}
